<template>
  <div>
    <el-input v-show="showSearch" placeholder="请输入搜索内容" v-model="search.text" @change="searchChangeHandler">
      <el-button icon="el-icon-search" type="primary" slot="append" @click="searchChangeHandler">搜索</el-button>
    </el-input>

    <el-table ref="dictTable" :data="pageList" border stripe highlight-current-row
              @current-change="rowChangeHandler">
      <el-table-column width="150px" property="code" label="编码"></el-table-column>
      <el-table-column width="300px" property="name" label="名称"></el-table-column>
    </el-table>

    <el-pagination background layout="total, prev, next, ->, slot" style="padding-top: 10px;"
                   :page-size="search.pageSize" :current-page="search.pageNumber" :total="search.total"
                   @current-change="pageChangeHandler">
      <el-button v-show="showRefresh" icon="el-icon-refresh" @click="refreshClickHandler">刷新</el-button>
      <el-button v-show="showClear" icon="el-icon-brush" @click="clearClickHandler">清空</el-button>
    </el-pagination>
  </div>
</template>

<script>
import $dict from "@/store/dict";

export default {
  name: "DictPanel",
  props: {
    dictKey: {
      type: String,
      required: true
    },
    current: [String, Number],
    showSearch: {
      type: Boolean,
      default: false
    },
    showRefresh: {
      type: Boolean,
      default: false
    },
    showClear: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      search: {
        text: '',
        pageNumber: 1,
        pageSize: 8,
        total: 0
      },
      pageList: [],
      allList: [],
      searchList: []
    };
  },
  created() {
    $dict.getData(this.dictKey).then(list => {
      this.allList = list;
      this.searchChangeHandler();
    });
  },
  watch: {
    current(newVal, oldVal) {
      if (newVal) {

      } else {
        this.$refs.dictTable.setCurrentRow();
      }
    }
  },
  methods: {
    searchChangeHandler() {
      if (this.search.text) {
        this.searchList = this.allList.filter(obj => {
          return String(obj.code).search(this.search.text) !== -1
            || String(obj.name).search(this.search.text) !== -1;
        });
      } else {
        this.searchList = this.allList;
      }
      this.search.total = this.searchList.length;
      this.pageChangeHandler(1);
    },
    pageChangeHandler(num) {
      this.search.pageNumber = num;
      this.pageList = this.searchList.slice((this.search.pageNumber - 1) * this.search.pageSize,
        this.search.pageNumber * this.search.pageSize);
    },
    rowChangeHandler(row) {
      this.$emit('change', Object.assign({}, row));
    },
    refreshClickHandler() {
      this.search.text = '';
      $dict.refresh(this.dictKey).then(list => {
        this.allList = list;
        this.searchChangeHandler();
      });
    },
    clearClickHandler() {
      this.$refs.dictTable.setCurrentRow();
    }
  }
}
</script>

<style scoped>

</style>
